#!/usr/bin/perl

### global variables ###

@warnings = ();

### main ###
if (system("cdrdao read-toc --device ATAPI:0,0,0 --driver generic-mmc-raw cd.toc")) {
	&print_error('cdrdao: cannot get toc file');
};
if (system("cdparanoia 1- data.wav")) {
	&print_error('Cannot run cdparanoia');
};

#if not working with dvd drive - try cd writer like that:
#cdparanoia -d /dev/cdroms/cdrom1 1- data.wav
#

exit(system("cdrdao write --overburn --device ATAPI:0,1,0 --speed 4 cd.toc"));

#if (system("cdparanoia -B")) {
#	&print_error('Cannot run cdparanoia');
#};
#&rename_tracks;

#&print_warnings;

### procedures ###
sub rename_tracks {
	if (!opendir(DIR_HANDLE, '.')) {
		&print_error('Cannot open current directory');
	};
	print "Renaming tracks...\n";
	foreach my $entry (readdir(DIR_HANDLE)) {
		next if ($entry =~ /^\.+$/);
		next if ($entry !~ /^track(\d+)\.cdda\.wav$/);
		my $new_name = "Track$1.wav";	
		print "$entry => $new_name\n";
		system ("mv $entry $new_name"); 
		if ($1 =~ /^0+$/) {
			push (@warnings, "The $new_name seems to be suspicious");
		};
	};
	closedir DIR_HANDLE;
};

sub print_error {
	my $message = shift;
	$message = "\nError:" . $message . "\n";
	print STDERR $message;
	exit(1);
};

sub print_warnings {
	return if (!scalar @warnings);
	foreach $warning (@warnings) {
		print STDERR "\nWARNING: $warning\n";
	};
};

#cdrdao read-toc --device 0,0,0 --driver generic-mmc-raw cd.toc
#cdparanoia 1- data.wav
#cdrdao write --device 0,1,0 --speed 4 cd.toc
